// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
require('./assets/style/reset.scss');
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import { API, HTTP, Vee, TOOL, FILTER } from './assets/scripts/ALL';

// 拦截 - 路由
router.beforeEach((to, from, next) => {
  if (to.meta.requireAccount) {
    if (localStorage.getItem('account_number')) {
      next();
    } else {
      next({
        path: '/new-account',
        query: {
          redirect: to.fullPath
        }
      });
    }
  } else if (to.meta.requireAuth) {
    if (localStorage.getItem('id') && localStorage.getItem('token')) {
      next();
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      });
    }
  } else {
    next();
  }
});

// todo 请求拦截 - 禁止点击

HTTP.axios.interceptors.request.use(function (config) {
  return config;
}, function (error) {
  return Promise.reject(error);
});

let Intercepted = false;

// 返回拦截 - 登录身份失效
HTTP.axios.interceptors.response.use(function (res) {

  if (res.data.error === 2 && !Intercepted) {
    Intercepted = true;
    localStorage.removeItem('id');
    localStorage.removeItem('token');
    alert('登录状态已失效，请重新登录');
    router.push({
      path: '/login',
      query: {
        redirect: window.location.hash.substr(1)
      }
    });

    // 异步执行
    setTimeout(function () {
      Intercepted = false;
    }, 2000);
  }

  // 返回到then
  return res;
}, function (error) {
  // 返回到catch
  return Promise.reject(error);
});

// 全局默认配置

// 接口
Vue.prototype.$api = API;

// HTTP 请求
Vue.prototype.$http = HTTP;

// 公共函数
Vue.prototype.$tool = TOOL;

// 验证
Vue.use(Vee.VeeValidator, Vee.VeeValidatorConfig);

// 过滤器
Object.keys(FILTER).forEach(key => {
  Vue.filter(key, FILTER[key])
});

// Vue.config.productionTip = true;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
});
